package com.ca.singlesignon.utils;

import avro.shaded.com.google.common.collect.Lists;
import com.ca.singlesignon.entity.UserEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.codehaus.jackson.type.JavaType;
import org.codehaus.jackson.type.TypeReference;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by Gary
 */
@Slf4j
public class JsonUtil {

    private static ObjectMapper objectMapper=new ObjectMapper();

    static{
        //ALWAYS 对象的所有字段全部列入   NON_NULL 不为空字段   NON_DEFAULT 如果有默认的字段，不json序列化
        objectMapper.setSerializationInclusion(Inclusion.ALWAYS);
        //取消默认转换timestamps的形式
        objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS,false);
        //忽略空Bean转json的错误
        objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS,false);
        //所有的日期格式都同意为以下样式，即yyy-MM-dd HH:mm:ss
        objectMapper.setDateFormat(new SimpleDateFormat(DateTimeUtil.STANDARD_FORMAT));
        //忽略在json字符串中存在，但是在java对象中不存在对应属性防止错误
        objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,false);
    }
   public static <T> String obj2String(T obj){
        if(obj ==null){
            return null;
        }
       try {
           return obj instanceof String ? (String)obj : objectMapper.writeValueAsString(obj);
       } catch (IOException e) {
            log.warn("Parse Object to String error",e);
           e.printStackTrace();
           return null;
       }
   }

   public static <T> String obj2StringPretty(T obj){
        if(obj ==null){
            return null;
        }
       try {
           return obj instanceof String ? (String)obj : objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
       } catch (IOException e) {
            log.warn("Parse Object to String error",e);
           return null;
       }
   }

   public static <T> T string2Obj(String str,Class<T> clazz){
        if(StringUtils.isEmpty(str)|| clazz==null){
            return null;
        }
       try {
           return clazz.equals(String.class)?(T)str:objectMapper.readValue(str,clazz);
       } catch (IOException e) {
           log.warn("Parse String to Object error",e);
           return null;
       }
   }

   //可以实现多类型的序列化方法
    public static <T> T string2Obj(String str, TypeReference<T> typeReference){
        if(StringUtils.isEmpty(str) || typeReference==null ){
            return null;
        }
        try {
            return (T)(typeReference.getType().equals(String.class)?str:objectMapper.readValue(str,typeReference));
        } catch (IOException e) {
            log.warn("Parse String to Object error",e);
            return null;
        }
    }
    //可以实现多类型的序列化方法
    public static <T> T string2Obj(String str, Class<?> collectionClass,Class<?>... classes){

        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClass, classes);
        try {
            return objectMapper.readValue(str,javaType);
        } catch (IOException e) {
            log.warn("Parse String to Object error",e);
            return null;
        }
    }
    public static void main(String[] args) {
        UserEntity user=new UserEntity();
        user.setId(1);
        user.setEmail("2582814861@qq.com");
        user.setCreateTime(new Date());
        UserEntity user2=new UserEntity();
        user2.setId(2);
        user2.setEmail("15881331550@163.com");
        List<UserEntity> list= Lists.newArrayList();
        list.add(user);
        list.add(user2);
        //对象序列化
        String user1Json=JsonUtil.obj2String(user);
        String user1JsonPretty=JsonUtil.obj2StringPretty(user);

        log.info("user1Json:{}",user1Json);

        log.info("user1JsonPretty:{}",user1JsonPretty);

        //反序列化

        UserEntity user1=JsonUtil.string2Obj(user1JsonPretty,UserEntity.class);

        log.info("user1JsonPretty:{}",user1);
        
        //集合序列化
        String listStr = JsonUtil.obj2StringPretty(list);

        log.info("==============:"+listStr);

        //集合反序列化使用上述方法不能成功一个，会被默认序列化成LinkedHashMap
        List<UserEntity> list1 = JsonUtil.string2Obj(listStr, new TypeReference<List<UserEntity>>(){});

        log.info("==============:"+list1);

        List<UserEntity> users = JsonUtil.string2Obj(listStr, List.class, UserEntity.class);
        log.info("===============:"+users);
    }
}
